23/04/2017

Proposta

  • R Básico
  • Estrutura e Conceitos do R
  • Importando Dados para o R
  • Data Wrangling e Tranformation
  • Visualização de Dado

Onde R é utilizado

  • Análise e Inferência Estatística;
  • Plots Exploratórios;
  • Análise Exploratória de Dados;
  • Produção Automática de Relatórios;
  • Machine Learning.

Porque Utilizar o R

  • Fácil e rápido de aprender;
  • Grande número de pacotes feitos e mantidos pela comunidade;
  • Fácil Integração com Mark-Down e Tex para produção de documentos;
  • Boas ferramentas para lidar com arquivos estruturados e bancos de dados relacionais e não relacionais;
  • Fácil integração com C, C++ e FOTRAN;
  • Uma das melhores IDEs, o RStudio.

R Básico

Funções de Ajuda

?mean #Ajuda de uma função
help.search(topic = 'linear regression') #Ajuda por termo de busca
help(package = 'dplyr') #Ajuda em um pacote
help(topic = mean) #Ajuda em uma função

R Básico

Criando Vetores

c(23, 5, -123)
## [1]   23    5 -123
1:10
##  [1]  1  2  3  4  5  6  7  8  9 10
seq(from = 0, to = 10, by = 2)
## [1]  0  2  4  6  8 10
rep(x = c(1,23,4), each = 3)
## [1]  1  1  1 23 23 23  4  4  4

R Básico

Selecionando Elementos por Posição

letters[1:5]
## [1] "a" "b" "c" "d" "e"
letters[c(4, 20)]
## [1] "d" "t"
letters[-(1:20)]
## [1] "u" "v" "w" "x" "y" "z"

R Básico

Selecionando Elementos por Valor

letters[letters == 'b']
## [1] "b"
letters[letters %in% c('a', 'd', 'e')]
## [1] "a" "d" "e"

R Básico

Selecionando Elementos por Nome

auxVet <- c(valA = 23, valB = 32, valC = -32)
auxVet['valB']
## valB 
##   32

Tipos de Dado

Integer:

  • Número pertencente ao conjunto \({\rm I\!N}\);

Numeric:

  • Número pertencente ao conjunto \({\rm I\!R}\);

Complex:

  • Número pertencente ao conjunto \({\rm I\!C}\);

Tipos de Dado

Character:

  • Characters ou Strings

Factor:

  • Variável Categórica

Dates:

  • Data formatada

Estruturas de Dado

Vetores :

  • É uma sequência de qualquer tipo de dado;
c('foo', 'bar', 'baz')
## [1] "foo" "bar" "baz"
c(-3.2, 4.6, 5.1)
## [1] -3.2  4.6  5.1
1:10
##  [1]  1  2  3  4  5  6  7  8  9 10

Estruturas de Dado

Matrix :

  • Estrutura bidimensional de tamanho pré-estabelecido para qualquer tipo de dado.
matrix(data = 1:6, ncol = 3, nrow = 2)
##      [,1] [,2] [,3]
## [1,]    1    3    5
## [2,]    2    4    6
matrix(data = c('foo', 'baz', 'bar', 'faz'),
       ncol = 2, nrow = 2)
##      [,1]  [,2] 
## [1,] "foo" "bar"
## [2,] "baz" "faz"

Estruturas de Dado

Arrays :

  • Estrutura multidimensional de tamanho pré-estabelecido para qualquer tipo de dado.
array(data = 1:12, dim = c(2,3,2))
## , , 1
## 
##      [,1] [,2] [,3]
## [1,]    1    3    5
## [2,]    2    4    6
## 
## , , 2
## 
##      [,1] [,2] [,3]
## [1,]    7    9   11
## [2,]    8   10   12

Estruturas de Dado

Data Frames :

  • Uma estrutura de dados bidimensional que pode ter tipos de dados diferentes em cada coluna.
data.frame(Name = c('John', 'Jack', 'Jose'),
           Age = c(20, 25, 22),
           Height = c(1.78, 1.92, 1.71))
##   Name Age Height
## 1 John  20   1.78
## 2 Jack  25   1.92
## 3 Jose  22   1.71

Estruturas de Dado

Listas :

  • Uma coleção de estrutar diferentes.
list(Supermarket = data.frame(
  Product = c('Soup', 'Potatoes', 'Tooth Paste'),
  Quantity = c(3, 20, 2)),
  Date = Sys.Date())
## $Supermarket
##       Product Quantity
## 1        Soup        3
## 2    Potatoes       20
## 3 Tooth Paste        2
## 
## $Date
## [1] "2017-05-03"

Controle de Fluxo

Loop

for(i in 1:5) {}
for(element in listOfThings) {}
while(condition == TRUE) {}
while(condition) {}

Controle de Fluxo

Condicional

if(condition == TRUE) {
  DoSomething()  
} if else(!condition2){
    DoSomethingElse()
} else{
    DoLastPossibleThing()
}
ifelse(test == TRUE, DoTrueThing(), DoFalseThing())

Controle de Fluxo

Condicional

switch(a, 
       'val1' = doVal1Thing(),
       'val2' = doVal2Thing(),
       doDefaultThing()
       )

Relational Operators

  • Menor que : '<'
  • Menor ou igual que : '<='
  • Maior que : '>'
  • Maior ou igual que : '>='
  • Exatamente igual a : '=='
  • Diferente de : '!='

R Básico - Operadores Lógicos

TRUE == 1
## [1] TRUE
12 != 'b'
## [1] TRUE
12 >= 12
## [1] TRUE

R Básico - Operadores Lógicos

10 > 9:11
## [1]  TRUE FALSE FALSE
rep(10, 3) == 9:11
## [1] FALSE  TRUE FALSE
9:11 == rep(10, 3)
## [1] FALSE  TRUE FALSE

R Básico - Operadores Lógicos

  • Not : '!'
!TRUE
## [1] FALSE
!2
## [1] FALSE
!FALSE
## [1] TRUE

R Básico - Operadores Lógicos

And : '&' or '&&'

TRUE & 1
## [1] TRUE
( (2:4) >= 3) & ( (2:4) <= 3)
## [1] FALSE  TRUE FALSE
( (2:4) >= 3) && ( (2:4) <= 3)
## [1] FALSE

R Básico - Operadores Lógicos

Or : '|' or '||'

( (2:4) >= 3) | ( (2:4) == 2)
## [1] TRUE TRUE TRUE
( (2:4) >= 3) || ( (2:4) == 2)
## [1] TRUE
( (2:4) >= 3) || ( (2:4) == 3)
## [1] FALSE

R Básico - Criando uma Funções

MyFun <- function(inputVal, someFlag = TRUE){
    val = numeric()
    if(someFlag){ 
        val = inputVal + 1
    } else{
        val = inputVal * -1
    }
    list(Val = val,
         Flag = someFlag)
}

R Básico - Criando uma Funções

MyFun(inputVal = 200)
## $Val
## [1] 201
## 
## $Flag
## [1] TRUE
MyFun(inputVal = 200, someFlag = FALSE)
## $Val
## [1] -200
## 
## $Flag
## [1] FALSE

R Básico - Funções Úteis

Carregando e Instalando Pacotes

install.packages(package = 'dplyr') #Instala pacote
library(package = 'dplyr') #Carrega Pacote, utilizar em ambiente global
require(package = 'dplyr') #Carrega Pacote, utilizar em ambiente inferiores

Lidando com Diretórios

getwd() #Pega diretório atual
setwd(dir = './../otherDirectory/') #Muda o diretório atual
dir(path = './') #Lista todos os arquivos e pastas do diretório

R Básico - Funções Úteis

Lidando com Arquivos

file.exists('input_file.txt')
file.create('output_file.xml')
file.remove('useless_file.csv')

Guardando Seção do R

save.image(file = 'my_env.Rdata') #Salva Ambiente Global
load(file = 'my_env.Rdata') #Carrega ambiente Global
saveRDS(object = myDF, file = 'my_env.rds') #Salva uma Variável
myDF <- readRDS(file = 'my_df.rds') #Carrega uma Variável

Interagindo com o Sistema

Sys.time() # Pega Hora do Sistema
system(command = 'python --version') #Roda comando na Terminal
Sys.sleep(1.5) #Faz o sistema Dormir

Important Functions

Imprimindo ao Usuário

print('R is super \'cools\'') #Imprime Raw Characters 
cat('R is super \'cools\'') #Imprime Como no 'C'

Outras funções

paste("R", ' is like a ', 10) #Junta Strings
## [1] "R  is like a  10"
class(x = 'Something') #Retorna classe do objeto
## [1] "character"
sample(x = 10, size = 3) # Retorna Sequencia Aleatória
## [1] 2 6 1
summary(object = iris)
##   Sepal.Length    Sepal.Width     Petal.Length    Petal.Width   
##  Min.   :4.300   Min.   :2.000   Min.   :1.000   Min.   :0.100  
##  1st Qu.:5.100   1st Qu.:2.800   1st Qu.:1.600   1st Qu.:0.300  
##  Median :5.800   Median :3.000   Median :4.350   Median :1.300  
##  Mean   :5.843   Mean   :3.057   Mean   :3.758   Mean   :1.199  
##  3rd Qu.:6.400   3rd Qu.:3.300   3rd Qu.:5.100   3rd Qu.:1.800  
##  Max.   :7.900   Max.   :4.400   Max.   :6.900   Max.   :2.500  
##        Species  
##  setosa    :50  
##  versicolor:50  
##  virginica :50  
##                 
##                 
## 

R Básico - Funções Úteis

Olhando um Data Set

head(iris)
##   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1          5.1         3.5          1.4         0.2  setosa
## 2          4.9         3.0          1.4         0.2  setosa
## 3          4.7         3.2          1.3         0.2  setosa
## 4          4.6         3.1          1.5         0.2  setosa
## 5          5.0         3.6          1.4         0.2  setosa
## 6          5.4         3.9          1.7         0.4  setosa
tail(iris, n = 2)
##     Sepal.Length Sepal.Width Petal.Length Petal.Width   Species
## 149          6.2         3.4          5.4         2.3 virginica
## 150          5.9         3.0          5.1         1.8 virginica

R Básico - Funções Úteis

Testando Tipo do Dado

is.na(NA)
## [1] TRUE
is.null(NULL)
## [1] TRUE
is.factor(LETTERS)
## [1] FALSE

R Básico - Funções Úteis

Mudando Tipo do Dado

as.factor(LETTERS[1:4])
## [1] A B C D
## Levels: A B C D
as.character(LETTERS[1:4])
## [1] "A" "B" "C" "D"
as.integer(c(1.5, pi))
## [1] 1 3

R Básico - Família Apply

  • apply();
  • sapply();
  • lapply();
  • mapply();
  • tapply();

R Básico - Família Apply

auxDF <- iris[1:5, 1:3]
print(auxDF)
##   Sepal.Length Sepal.Width Petal.Length
## 1          5.1         3.5          1.4
## 2          4.9         3.0          1.4
## 3          4.7         3.2          1.3
## 4          4.6         3.1          1.5
## 5          5.0         3.6          1.4

R Básico - Família Apply

apply(auxDF , 1, mean )
##        1        2        3        4        5 
## 3.333333 3.100000 3.066667 3.066667 3.333333
apply(auxDF , 2, mean )
## Sepal.Length  Sepal.Width Petal.Length 
##         4.86         3.28         1.40

R Básico - Família Apply

auxListA <- list( a = 1:5, b = seq(0, 1, 0.25))
auxListB <- list( c = 5:1, d = -seq(0, 1, 0.25))
print(auxListA)
## $a
## [1] 1 2 3 4 5
## 
## $b
## [1] 0.00 0.25 0.50 0.75 1.00
print(auxListB)
## $c
## [1] 5 4 3 2 1
## 
## $d
## [1]  0.00 -0.25 -0.50 -0.75 -1.00

R Básico - Família Apply

sapply(X = auxListA, FUN = sum )
##    a    b 
## 15.0  2.5
lapply(X = auxListA, FUN = sum )
## $a
## [1] 15
## 
## $b
## [1] 2.5

R Básico - Família Apply

mapply(FUN = sum, auxListA, auxListB)
##  a  b 
## 30  0
tapply(X = 1:10, INDEX = rep(x = c('a', 'b'), each = 5 ), FUN = mean)
## a b 
## 3 8

R Básico - Família Apply

Outras funções

  • vapply();
  • rapply();
  • eapply();
  • dendrapply();
  • etc.

Estrutura e Conceitos do R

Estrutura e Conceitos do R

Empty environment - Pai de Todos os Ambientes

  • Parent: none
  • Accesso: emptyenv()

Base environment - Ambiente do R base package

  • Parent: empty environment
  • Accesso: baseenv()

Global environment – Ambiente Normal de trabalho

  • Parent: Ambiente do Ultimo pacote carregado
  • Accesso : globalenv()

Current environment – Ambiente onde o R está rodando (pode ser um dos anteriores)

  • Parent: empty environment
  • Accesso: environment()

Estrutura e Conceitos do R

Estrutura e Conceitos do R - Guia de Etiqueta R

  • Arquivo = predict_ad_revenue.R
  • Variável = vgClicks
  • Função = CalculateAvgClicks
  • Tamanho da Lina <= 80 characters
  • Espaçamento = Sempre colocar espaço entre operadores ex: (if (debug), x + y)
  • Função de Pacote = packageName::packageFun()

Estrutura e Conceitos do R - Guia de Etiqueta R

Tabs

plot(x    = x.coord,
     y    = data.mat[, MakeColName(metric, ptiles[1], "roiOpt")],
     ylim = ylim,
     xlab = "dates",
     ylab = metric,
     main = (paste(metric, " for 3 samples ", sep = "")))
plot(x = x.coord,
     y = data.mat[, MakeColName(metric, ptiles[1], "roiOpt")],
     ylim = ylim,
     xlab = "dates",
     ylab = metric,
     main = (paste(metric, " for 3 samples ", sep = "")))

Estrutura e Conceitos do R - Guia de Etiqueta R

Chaves

if (condition) {
  one or more lines
} else {
  one or more lines
}

if (is.null(ylim)) runFun()

Importando Dados para o R

Importando Dados para o R

  • readr : Arquivos Texto(txt, csv, etc)
  • readxl :xl e xlsx
  • jsonlite :json
  • xml2 :xml
  • DBI :DB
  • httr :Web Api
  • rvest :Web Scrapping

Importando Dados para o R

readr - Funções

  • readr::read_csv()
  • readr::read_csv2()
  • readr::read_tsv()
  • readr::read_table()
  • readr::read_table2()
  • readr::readr::read_delim()

Importando Dados para o R

readr - Funções

  • file = nome do arquivo
  • delim = character de separação entre valores
  • quote = character que mostr ser string
  • na = character que é o valor de NA
  • skip = número de linhas do cabeçalho
  • col_names = nome das colunas
  • col_types = tipo das colunas
  • comment = string de comentários
  • n_max = número máximo de linhas

Tidyverse

Tidyverse

Tidyverse

  • RStudio
  • Hadley Wickham
  • WICKHAM, Hadley . Tidy Data. Journal of Statistical Software, [S.l.], v. 59, Issue 10, p. 1 - 23, sep. 2014. ISSN 1548-7660

Tidyverse

Tidy Data

  • Cada variável é uma coluna.
  • Cada observação é uma linha.
  • Cada tipo de unidade de observação forma uma tabela.

Data Wrangling e Tranformation

Data Wrangling e Tranformation

Pacotes

  • tidyr
  • dplyr

Data Wrangling e Tranformation

Data Wrangling e Tranformation

Data Wrangling e Tranformation

Funções tidyr

  • tidyr::gather
  • tidyr::spread
  • tidyr::separate
  • tidyr::unite

Data Wrangling e Tranformation

tidyr::gather

Data Wrangling e Tranformation

tidyr::spread

Data Wrangling e Tranformation

Funções tidyr

iris %>%
  tidyr::gather(key = flowerVar, value = flowerValue, -Species) %>%
  dplyr::sample_n(5)
##        Species    flowerVar flowerValue
## 333     setosa Petal.Length         1.5
## 202 versicolor  Sepal.Width         3.2
## 253  virginica  Sepal.Width         3.0
## 536 versicolor  Petal.Width         1.6
## 452     setosa  Petal.Width         0.2

Data Wrangling e Tranformation

Funções tidyr

iris %>%
  tibble::rownames_to_column(var = 'Obs') %>%
  tidyr::gather(key = flowerVar, value = flowerValue, -Species, -Obs) %>% 
  tidyr::spread(key = flowerVar, value = flowerValue) %>%
  dplyr::sample_n(5)
##     Obs    Species Petal.Length Petal.Width Sepal.Length Sepal.Width
## 100  53 versicolor          4.9         1.5          6.9         3.1
## 74    3     setosa          1.3         0.2          4.7         3.2
## 104  57 versicolor          4.7         1.6          6.3         3.3
## 65   21     setosa          1.7         0.2          5.4         3.4
## 42  136  virginica          6.1         2.3          7.7         3.0

Data Wrangling e Tranformation

Funções tidyr

iris %>%
  tidyr::gather(key = flowerVar, value = flowerValue, -Species) %>%
  tidyr::unite(col = newKey, Species, flowerVar, sep = '_') %>%
  dplyr::sample_n(5)
##                      newKey flowerValue
## 143  virginica_Sepal.Length         5.8
## 363 versicolor_Petal.Length         4.0
## 296   virginica_Sepal.Width         3.0
## 87  versicolor_Sepal.Length         6.7
## 467      setosa_Petal.Width         0.4

Data Wrangling e Tranformation

Funções tidyr

iris %>%
  tidyr::gather(key = flowerVar, value = flowerValue, -Species) %>%
  tidyr::separate(col = flowerVar, into = c('Type', 'Mesure')) %>%
  dplyr::sample_n(5)
##        Species  Type Mesure flowerValue
## 71  versicolor Sepal Length         5.9
## 164     setosa Sepal  Width         3.0
## 263  virginica Sepal  Width         3.0
## 206 versicolor Sepal  Width         2.8
## 181     setosa Sepal  Width         3.1

Data Wrangling e Tranformation

Funções dplyr - Básicas

  • dplyr::%>%
  • dplyr::filter
  • dplyr::select
  • dplyr::mutate
  • dplyr::arrange
  • dplyr::group_by
  • dplyr::summarise

Data Wrangling e Tranformation

Funções dplyr - Básicas

iris %>%
    dplyr::filter(Species != 'setosa') %>%
    dplyr::mutate(PL = Petal.Length + Petal.Width,
                  SP = Sepal.Length + Sepal.Width) %>%
    dplyr::select(Species, PL, SP) %>%
    dplyr::group_by(Species) %>%
    dplyr::summarise(meanPL = mean(PL), maxSP = max(SP)) %>%
    dplyr::arrange(Species)
## # A tibble: 2 × 3
##      Species meanPL maxSP
##       <fctr>  <dbl> <dbl>
## 1 versicolor  5.586  10.2
## 2  virginica  7.578  11.7

Data Wrangling e Tranformation

Funções dplyr - Subset por linha

  • dplyr::distinct remove todos os valores duplicados
  • dplyr::sample_frac seleciona linhas de forma aleatória
  • dplyr::sample_n seleciona linhas de forma aleatória
  • dplyr::top_n seleciona as primeiras linhas
  • dplyr::slice seleciona linhas pelas posições

Data Wrangling e Tranformation

Funções dplyr - Subset por linha

iris %>%
    dplyr::slice(c(12, 66, 100))
##   Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
## 1          4.8         3.4          1.6         0.2     setosa
## 2          6.7         3.1          4.4         1.4 versicolor
## 3          5.7         2.8          4.1         1.3 versicolor
iris %>%
    dplyr::sample_frac(0.02)
##     Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
## 40           5.1         3.4          1.5         0.2     setosa
## 86           6.0         3.4          4.5         1.6 versicolor
## 128          6.1         3.0          4.9         1.8  virginica

Data Wrangling e Tranformation

Funções dplyr - Subset por linha

iris %>%
    dplyr::group_by(Species) %>%
    dplyr::top_n(1, Petal.Length)
## Source: local data frame [4 x 5]
## Groups: Species [3]
## 
##   Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
##          <dbl>       <dbl>        <dbl>       <dbl>     <fctr>
## 1          4.8         3.4          1.9         0.2     setosa
## 2          5.1         3.8          1.9         0.4     setosa
## 3          6.0         2.7          5.1         1.6 versicolor
## 4          7.7         2.6          6.9         2.3  virginica

Data Wrangling e Tranformation

Funções dplyr - Subset por Coluna

  • dplyr::select( dplyr::contains() )
  • dplyr::select( dplyr::ends_with() )
  • dplyr::select( dplyr::everything() )
  • dplyr::select( dplyr::matches() )
  • dplyr::select( dplyr::num_range() )
  • dplyr::select( dplyr::one_of() )
  • dplyr::select( dplyr::starts_with() )
  • dplyr::select( FirstColumnName : LastColumnName )
  • dplyr::select( -RemovableColumnName )

Data Wrangling e Tranformation

Funções dplyr - Subset por Coluna - Regular Expression

Data Wrangling e Tranformation

Funções dplyr - Subset por Coluna

iris %>%
    dplyr::group_by(Species) %>%
    dplyr::sample_n(1) %>% 
    dplyr::ungroup() %>%
    dplyr::select(dplyr::ends_with('Length'))
## # A tibble: 3 × 2
##   Sepal.Length Petal.Length
##          <dbl>        <dbl>
## 1          5.4          1.7
## 2          6.4          4.5
## 3          6.4          5.3

Data Wrangling e Tranformation

Funções dplyr - Subset por Coluna

iris %>%
    dplyr::group_by(Species) %>%
    dplyr::sample_n(1) %>% 
    dplyr::ungroup() %>%
    dplyr::select(dplyr::contains('al'))
## # A tibble: 3 × 4
##   Sepal.Length Sepal.Width Petal.Length Petal.Width
##          <dbl>       <dbl>        <dbl>       <dbl>
## 1          4.8         3.0          1.4         0.3
## 2          5.6         2.9          3.6         1.3
## 3          6.2         3.4          5.4         2.3

Data Wrangling e Tranformation

Funções dplyr - Subset por Coluna

iris %>%
    dplyr::group_by(Species) %>%
    dplyr::sample_n(1) %>% 
    dplyr::ungroup() %>%
    dplyr::select(dplyr::matches('.[s]'))
## # A tibble: 3 × 1
##      Species
##       <fctr>
## 1     setosa
## 2 versicolor
## 3  virginica

Data Wrangling e Tranformation

Funções dplyr - Criando novas Colunas

  • dplyr::mutate
  • dplyr::mutate_each
  • dplyr::mutate_if
  • dplyr::mutate_at
  • dplyr::mutate_all
  • dplyr::transmute

Data Wrangling e Tranformation

Funções dplyr - Criando novas Colunas

iris %>%
    dplyr::select(Sepal.Length : Petal.Length) %>%
    dplyr::sample_n(3) %>%
    dplyr::mutate_each(funs = dplyr::funs(myMean = mean),
                       dplyr::matches('Sepal') )
##   Sepal.Length Sepal.Width Petal.Length Sepal.Length_myMean
## 1          6.5         3.0          5.8            5.566667
## 2          5.4         3.7          1.5            5.566667
## 3          4.8         3.4          1.6            5.566667
##   Sepal.Width_myMean
## 1           3.366667
## 2           3.366667
## 3           3.366667

Data Wrangling e Tranformation

Funções dplyr - Criando novas Colunas

iris %>%
    dplyr::group_by(Species) %>% 
    dplyr::sample_n(1) %>%
    dplyr::ungroup() %>%
    dplyr::transmute(Species = Species %>% as.numeric)
## # A tibble: 3 × 1
##   Species
##     <dbl>
## 1       1
## 2       2
## 3       3

Data Wrangling e Tranformation

Funções dplyr - Criando novas Colunas

iris %>%
    head() %>%
    dplyr::mutate_if(is.factor,
                     dplyr::funs( ifelse( is.na(.), 0, .) ) )
##   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1          5.1         3.5          1.4         0.2       1
## 2          4.9         3.0          1.4         0.2       1
## 3          4.7         3.2          1.3         0.2       1
## 4          4.6         3.1          1.5         0.2       1
## 5          5.0         3.6          1.4         0.2       1
## 6          5.4         3.9          1.7         0.4       1

Data Wrangling e Tranformation

Funções dplyr - Joins

  • dplyr::left_join
  • dplyr::right_join
  • dplyr::full_join
  • dplyr::inner_join
  • dplyr::semi_join
  • dplyr::anti_join

Data Wrangling e Tranformation

Funções dplyr - Joins

Data Wrangling e Tranformation

Funções dplyr - Joins

table01 <- iris %>%
            dplyr::filter(Species != 'virginica') %>%
            dplyr::group_by(Species) %>% 
            dplyr::summarise(meanPL = mean(Petal.Length)) %>%
            dplyr::ungroup()
table02 <- iris %>%
            dplyr::filter(Species != 'setosa') %>%
            dplyr::group_by(Species) %>% 
            dplyr::summarise(medianPL = median(Petal.Length)) %>%
            dplyr::ungroup()

Data Wrangling e Tranformation

Funções dplyr - Joins

print(table01)
## # A tibble: 2 × 2
##      Species meanPL
##       <fctr>  <dbl>
## 1     setosa  1.462
## 2 versicolor  4.260
print(table02)
## # A tibble: 2 × 2
##      Species medianPL
##       <fctr>    <dbl>
## 1 versicolor     4.35
## 2  virginica     5.55

Data Wrangling e Tranformation

Funções dplyr - Joins

dplyr::inner_join(x = table01, y = table02, by = 'Species')
## # A tibble: 1 × 3
##      Species meanPL medianPL
##       <fctr>  <dbl>    <dbl>
## 1 versicolor   4.26     4.35
dplyr::full_join(x = table01, y = table02, by = 'Species')
## # A tibble: 3 × 3
##      Species meanPL medianPL
##       <fctr>  <dbl>    <dbl>
## 1     setosa  1.462       NA
## 2 versicolor  4.260     4.35
## 3  virginica     NA     5.55

Data Wrangling e Tranformation

Funções dplyr - Joins

dplyr::left_join(x = table01, y = table02, by = 'Species')
## # A tibble: 2 × 3
##      Species meanPL medianPL
##       <fctr>  <dbl>    <dbl>
## 1     setosa  1.462       NA
## 2 versicolor  4.260     4.35
dplyr::right_join(x = table01, y = table02, by = 'Species')
## # A tibble: 2 × 3
##      Species meanPL medianPL
##       <fctr>  <dbl>    <dbl>
## 1 versicolor   4.26     4.35
## 2  virginica     NA     5.55

Data Wrangling e Tranformation

Funções dplyr - Joins

dplyr::semi_join(x = table01, y = table02, by = 'Species')
## # A tibble: 1 × 2
##      Species meanPL
##       <fctr>  <dbl>
## 1 versicolor   4.26
dplyr::anti_join(x = table01, y = table02, by = 'Species')
## # A tibble: 1 × 2
##   Species meanPL
##    <fctr>  <dbl>
## 1  setosa  1.462

Data Wrangling e Tranformation

Funções dplyr - Juntando Data Frames

  • dplyr::bind_rows
  • dplyr::bind_cols

Data Wrangling e Tranformation

Funções dplyr - Juntando Data Frames

dplyr::bind_cols(table01, table02)
## # A tibble: 2 × 4
##      Species meanPL    Species medianPL
##       <fctr>  <dbl>     <fctr>    <dbl>
## 1     setosa  1.462 versicolor     4.35
## 2 versicolor  4.260  virginica     5.55
dplyr::bind_rows(table01, table02)
## # A tibble: 4 × 3
##      Species meanPL medianPL
##       <fctr>  <dbl>    <dbl>
## 1     setosa  1.462       NA
## 2 versicolor  4.260       NA
## 3 versicolor     NA     4.35
## 4  virginica     NA     5.55

Data Wrangling e Tranformation

Funções dplyr - Opearções de Conjunto

  • dplyr::intersect
  • dplyr::union
  • dplyr::setdiff

Data Wrangling e Tranformation

Funções dplyr - Operações de Conjunto

Data Wrangling e Tranformation

Funções dplyr - Opearções de Conjunto

dplyr::intersect(x = iris[1:3, ], y = iris[2:4, ])
##   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1          4.9         3.0          1.4         0.2  setosa
## 2          4.7         3.2          1.3         0.2  setosa
dplyr::setdiff(x = iris[1:3, ], y = iris[2:4, ])
##   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1          5.1         3.5          1.4         0.2  setosa

Data Wrangling e Tranformation

Funções dplyr - Opearções de Conjunto

dplyr::union(x = iris[1:3, ], y = iris[2:4, ])
##   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1          4.6         3.1          1.5         0.2  setosa
## 2          4.7         3.2          1.3         0.2  setosa
## 3          4.9         3.0          1.4         0.2  setosa
## 4          5.1         3.5          1.4         0.2  setosa

Visualização de Dados

Visualização de Dados

Pacotes

  • ggplot2
  • plotly

Visualização de Dados - ggplot2

Idéias Básicas

  • Pensar no Tipo da variável (Contínua, Discreta ou Fator).
  • Pensar nas cores e seus significados.
  • Pensar como cada variável pode ser codificada.

Visualização de Dados - ggplot2

Visualização de Dados - ggplot2

Visualização de Dados - ggplot2

ggplto2 - Uma Variável - Continua

Data <- data.frame(X = log10(1:100) ,
                   Y = sin(1:100 * 0.04) + 0.025 * rnorm(n = 100) )
p <- ggplot2::ggplot(data= Data, aes(x = Y))

ggplto2 - Uma Variável - Contínua

Histograma

p + ggplot2::geom_histogram(binwidth = 0.2) 

ggplto2 - Uma Variável - Contínua

Densidade

p + ggplot2::geom_density(adjust = 1, kernel = "gaussian") 

ggplto2 - Uma Variável - Contínua

Densidade Culmulativa

p + ggplot2::stat_ecdf(geom = "step", n = 10) 

ggplto2 - Duas Variável - Contínua

line, point, e smooth plots

ggplot2::ggplot(data = Data, aes(x = X, y = Y)) +
  ggplot2::geom_line() +
  ggplot2::geom_point() +
  ggplot2::geom_smooth(method = "lm")

ggplto2 - Duas Variável - 1 Contínua e 1 Discreta

bar plots

Data$Y <- round(abs(Data$Y) * 4 )
ggplot2::ggplot(data = Data, aes(x = factor(Y), y = X)) +
  ggplot2::geom_bar(stat = "identity") +
  ggplot2::coord_flip()

ggplto2 - Duas Variável - 1 Continua e 1 Discreta

box plot

ggplot2::ggplot(data = Data, aes(x = factor(Y), y = X)) +
  ggplot2::geom_boxplot()

ggplto2 - Duas Variável - 1 Continua e 1 Discreta

silhueta plot

ggplot2::ggplot(data = Data, aes(x = factor(Y), y = X)) +
  ggplot2::geom_violin()

Adicionando Novas Variávies

Novas variáveis podem ser codificadas no gráfico por meio de : - Grupos - Cor - Tamanho - Preenchimento

ggplot2::aes()

  • x
  • y
  • z
  • alpha
  • colour
  • fill
  • group
  • linetype
  • size
  • shape

ggplot2::labs

ggplot2::ggplot(data = iris,
                aes(x = Sepal.Length, y = Sepal.Width,
                    size = Petal.Length / 2,
                    shape = factor(round(Petal.Width)),
                    color = Species)) + 
  ggplot2::geom_point() + 
  ggplot2::labs(title = 'Titulo', subtitle = 'Subtitulo',
                x = 'Titulo X', y = 'Titulo Y',
                colour = "Legenda Cor",
                caption = 'Rodape',
                shape = 'Legenda Formato',
                size = 'Legenda Tamanho')  + 
  ggplot2::theme(
    legend.justification = c("left", "top"),
    legend.margin = margin(2, 2, 2, 2) )

ggplot2::labs

ggplot - Extensões

  • ggthemes
  • ggtech
  • ggmap
  • ggforce
  • ggTimeSeries
  • ggradar
  • ggraph
  • geomnet
  • ggnetwork
  • gganimate
  • ggiraph

ggplot - Extensões

  • ggdendro
  • corrplot
  • ggfortify
  • plotROC
  • plotly

plotly - plotly::ggplotly

p <- iris %>%
      tidyr::gather(key = IrisVar, value = IrisVal, -Species) %>%
      ggplot2::ggplot(aes(x = IrisVar, group = Species,
                          y = IrisVal, fill = Species)) +
      ggplot2::geom_bar(stat = "identity", position = "dodge")
p

plotly - plotly::ggplotly

plotly::ggplotly(p = p)

plotly - lines

head(TemperatureData)
##      month high_2000 low_2000 high_2007 low_2007 high_2014 low_2014
## 1  January      32.5     13.8      36.5     23.6      28.8     12.7
## 2 February      37.6     22.3      26.6     14.0      28.5     14.3
## 3    March      49.9     32.5      43.6     27.0      37.0     18.6
## 4    April      53.0     37.2      52.3     36.8      56.8     35.5
## 5      May      69.1     49.9      71.5     47.6      69.7     49.9
## 6     June      75.4     56.1      81.4     57.7      79.7     58.0

plotly - lines

p <- plot_ly(TemperatureData,
             x = ~month, y = ~high_2014, 
             name = 'High 2014',
             type = 'scatter', mode = 'lines',
             line = list(color = 'rgb(205, 12, 24)', width = 4)
             )

plotly - lines

p <- p %>%
      add_trace(y = ~low_2014, name = 'Low 2014',
                line = list(color = 'rgb(22, 96, 167)',
                            width = 4)) %>%
      add_trace(y = ~high_2007, name = 'High 2007',
                line = list(color = 'rgb(205, 12, 24)', 
                            width = 4, dash = 'dash')) %>%
      add_trace(y = ~low_2007, name = 'Low 2007',
                line = list(color = 'rgb(22, 96, 167)', 
                            width = 4, dash = 'dash')) %>%
      add_trace(y = ~high_2000, name = 'High 2000',
                line = list(color = 'rgb(205, 12, 24)',
                            width = 4, dash = 'dot')) %>%
      add_trace(y = ~low_2000, name = 'Low 2000', 
                line = list(color = 'rgb(22, 96, 167)', 
                            width = 4, dash = 'dot'))

plotly - lines

p <- p %>%
      layout(title = "Average High and Low Temperatures in New York",
             xaxis = list(title = "Months"),
             yaxis = list (title = "Temperature (degrees F)"))

plotly - lines

plotly - scatter

p <- plot_ly(data = iris, x = ~Sepal.Length, y = ~Petal.Length,
             color = ~Species,
             type = 'scatter', mode = 'markers', 
             marker = list(size = 10)
             ) %>%
  layout(title = 'Styled Scatter',
         yaxis = list(zeroline = FALSE),
         xaxis = list(zeroline = FALSE))

plotly - scatter

p

plotly - pie

USPersonalExpenditure
##                               Categorie X1960
## Food and Tobacco       Food and Tobacco 86.80
## Household Operation Household Operation 46.20
## Medical and Health   Medical and Health 21.10
## Personal Care             Personal Care  5.40
## Private Education     Private Education  3.64

plotly - pie

plot_ly(USPersonalExpenditure, labels = ~Categorie,
        values = ~X1960, type = 'pie') %>%
  layout(title = 'US Expenditures 1960',
         xaxis = list(showgrid = FALSE, zeroline = FALSE,
                      showticklabels = FALSE),
         yaxis = list(showgrid = FALSE, zeroline = FALSE,
                      showticklabels = FALSE))

plotly - bar

Animals <- c("giraffes", "orangutans", "monkeys")
SF_Zoo <- c(20, 14, 23)
LA_Zoo <- c(12, 18, 29)
ZooData <- data.frame(Animals, SF_Zoo, LA_Zoo)
ZooData
##      Animals SF_Zoo LA_Zoo
## 1   giraffes     20     12
## 2 orangutans     14     18
## 3    monkeys     23     29

plotly - bar

plotly::plot_ly(ZooData, x = ~Animals, y = ~SF_Zoo,
        type = 'bar', name = 'SF Zoo') %>%
  plotly::add_trace(y = ~LA_Zoo, name = 'LA Zoo') %>%
  plotly::layout(yaxis = list(title = 'Count'),
                 barmode = 'group')

plotly - histogram

plotly::plot_ly(alpha = 0.6) %>%
  plotly::add_histogram(x = ~rnorm(500)) %>%
  plotly::add_histogram(x = ~rnorm(500) + 1) %>%
  plotly::layout(barmode = "overlay")

plotly - boxplot

plotly::plot_ly(ggplot2::diamonds, x = ~cut, y = ~price, 
        color = ~clarity, type = "box") %>%
  plotly::layout(boxmode = "group")

plotly - Heatmap

plotly::plot_ly(z = volcano, type = "heatmap")

plotly - 3dSurface

plotly::plot_ly(z = ~volcano) %>% 
  plotly::add_surface()

plotly - 3dSurface

 plotly::plot_ly(type = 'mesh3d',
  x = c(0, 0, 1, 1, 0, 0, 1, 1),
  y = c(0, 1, 1, 0, 0, 1, 1, 0),
  z = c(0, 0, 0, 0, 1, 1, 1, 1),
  i = c(7, 0, 0, 0, 4, 4, 6, 6, 4, 0, 3, 2),
  j = c(3, 4, 1, 2, 5, 6, 5, 2, 0, 1, 6, 3),
  k = c(0, 7, 2, 3, 6, 7, 1, 1, 5, 5, 7, 6),
  intensity = seq(0, 1, length = 8),
  color = seq(0, 1, length = 8),
  colors = colorRamp(rainbow(8))
)

plotly - 3dSurface